package com.mall.untils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("accessTokenService")
public class AccessTokenService {

    private Logger logger = LoggerFactory.getLogger(AccessTokenService.class);

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * access_token是公众号的全局唯一票据，公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒，重复获取将导致上次获取的access_token失效。由于获取access_token的api调用次数非常有限，建议开发者全局存储与更新access_token，频繁刷新access_token会导致api调用受限，影响自身业务。
     * 这里使用数据库将access_token存起来，这个表只有一条记录
     */
    public static String tableName = "t_e_access_token";


    /**
     * 增加access_token记录
     *
     * @param accessToken
     * @return
     */
    public boolean add(String accessToken) {

        Map<String, Object> accessTokenMap = get();
        int update;

        if (accessTokenMap == null || accessTokenMap.size() < 1) {
            String sql = "insert into " + tableName + " (access_token, last_time) values (?, ?)";
            update = jdbcTemplate.update(sql, accessToken, System.currentTimeMillis() / 1000);
        } else {
            String sql = "update " + tableName + " set access_token=?, last_time=?, created_time=now()";
            update = jdbcTemplate.update(sql, accessToken, System.currentTimeMillis() / 1000);
        }


        logger.debug("update =======>" + update);
        return update > 0;
    }


    /**
     * 获取access token记录
     *
     * @return
     */
    public Map<String, Object> get() {
        String sql = "SELECT * FROM t_e_access_token limit 1";
        List<Map<String, Object>> queryList = jdbcTemplate.queryForList(sql);
        logger.info("查询当前的token：" + sql);
        logger.info("queryList:" + queryList.toString());

        if (queryList != null && queryList.size() > 0) {

            logger.info("查询当前的token非空");
            return queryList.get(0);
        } else {
            logger.info("查询当前的token为空");
            return null;
        }
    }

    /**
     * 清除之前的access_token
     */
    public void delete() {
        String sql = "delete FROM " + tableName;
        jdbcTemplate.execute(sql);
    }

}


